<template>
  <div>
    <div class="page" v-if="!state.showDetail">
      <div class="listWrap" :class="state.listActive == true ? 'on' : ''">
        <div class="list">
          <a-button
            style="color: #165dff; border-color: #165dff"
            v-auth="'hp-admin:patientManagement:addGroup'"
            @click="aiGroupBtn"
            >+ AI智能分组</a-button
          >
          <a-button
            v-for="(item, index) of state.tabButtons"
            :key="index"
            type="text"
            :class="['tab_buttons', item.check ? 'checked' : '']"
            @click="selectGroup(item)"
            >{{ item.groupName }}</a-button
          >
        </div>
        <DownCircleOutlined :class="state.listActive == true ? 'on' : ''" @click="upfun" />
      </div>
      <div class="body">
        <div class="header">
          <!-- 搜索条件 -->
          <div class="search_condition">
            <a-form layout="inline" class="search-form">
              <a-form-item label="性别">
                <a-select
                  :value="state.sex"
                  :disabled="state.favorite"
                  placeholder="请选择"
                  @change="handleSexChange"
                  :getPopupContainer="
                    (triggerNode) =>
                      triggerNode.parentNode.parentNode.parentNode.parentNode.parentNode
                  "
                >
                  <a-select-option value="">全部</a-select-option>
                  <a-select-option value="1">男性</a-select-option>
                  <a-select-option value="2">女性</a-select-option>
                </a-select>
              </a-form-item>
              <a-form-item label="管理医生">
                <a-select
                  :value="state.doctor"
                  placeholder="请选择"
                  :disabled="state.favorite"
                  allowClear
                  @change="handleDoctor"
                  :getPopupContainer="
                    (triggerNode) =>
                      triggerNode.parentNode.parentNode.parentNode.parentNode.parentNode
                  "
                >
                  <a-select-option :key="-1" :value="''">全部</a-select-option>
                  <a-select-option
                    v-for="(item, index) in state.doctorList"
                    :key="index"
                    :value="item.user_id"
                  >
                    {{ item.user_name }}
                  </a-select-option>
                </a-select>
              </a-form-item>
              <a-form-item label="专病分组">
                <a-select
                  :value="state.group"
                  mode="multiple"
                  placeholder="请选择"
                  :max-tag-count="0"
                  @change="handleGroup"
                  optionFilterProp="label"
                  :disabled="state.favorite"
                  :allowClear="true"
                  showArrow
                  :getPopupContainer="
                    (triggerNode) =>
                      triggerNode.parentNode.parentNode.parentNode.parentNode.parentNode
                  "
                >
                  <a-select-option
                    v-for="(item, index) in state.tabButtons"
                    :key="index"
                    :value="item.id"
                    :label="item.groupName"
                    >{{ item.groupName }}</a-select-option
                  >
                  <template #maxTagPlaceholder="omittedValues">
                    <span v-if="state.tabButtons.length != omittedValues.length">
                      {{ omittedValues.length }}个标签
                    </span>
                    <span v-else>全部</span>
                  </template>
                </a-select>
              </a-form-item>
              <a-form-item>
                <a-input-search
                  v-model:value="state.searchValue"
                  placeholder="请输入患者姓名"
                  style="width: 200px"
                  @search="onSearch"
                />
              </a-form-item>
              <a-form-item>
                <a-button @click="resetEvent">重置</a-button>
              </a-form-item>
            </a-form>
            <!-- <div class="search_select">
              <span class="span-label">性别</span>
              <a-select
                :value="state.sex"
                :disabled="state.favorite"
                placeholder="请选择"
                @change="handleSexChange"
                :getPopupContainer="(triggerNode) => triggerNode.parentNode.parentNode.parentNode"
              >
                <a-select-option value="">全部</a-select-option>
                <a-select-option value="1">男性</a-select-option>
                <a-select-option value="2">女性</a-select-option>
              </a-select>
            </div>
            <div class="search_select">
              <span class="span-label">管理医生</span>
              <a-select
                :value="state.doctor"
                placeholder="请选择"
                :disabled="state.favorite"
                allowClear
                @change="handleDoctor"
                :getPopupContainer="(triggerNode) => triggerNode.parentNode.parentNode"
              >
                <a-select-option :key="-1" :value="''">全部</a-select-option>
                <a-select-option
                  v-for="(item, index) in state.doctorList"
                  :key="index"
                  :value="item.user_id"
                >
                  {{ item.user_name }}
                </a-select-option>
              </a-select>
            </div>
            <div class="search_select">
              <span class="span-label">专病分组</span>
              <a-select
                :value="state.group"
                mode="multiple"
                placeholder="请选择"
                :max-tag-count="0"
                @change="handleGroup"
                optionFilterProp="label"
                :disabled="state.favorite"
                :allowClear="true"
                showArrow
                :getPopupContainer="(triggerNode) => triggerNode.parentNode.parentNode.parentNode"
              >
                <a-select-option
                  v-for="(item, index) in state.tabButtons"
                  :key="index"
                  :value="item.id"
                  :label="item.groupName"
                  >{{ item.groupName }}</a-select-option
                >
                <template #maxTagPlaceholder="omittedValues">
                  <span v-if="state.tabButtons.length != omittedValues.length">
                    {{ omittedValues.length }}个标签
                  </span>
                  <span v-else>全部</span>
                </template>
              </a-select>
            </div>

            <a-button @click="resetEvent">重置</a-button>
            <div class="search_input">
              <a-input-search
                v-model:value="state.searchValue"
                placeholder="请输入患者姓名"
                style="width: 200px"
                @search="onSearch"
              />
            </div> -->
          </div>
          <!-- 表格操作 -->
          <div class="total_operate">
            <span style="color: #000000d9">共筛选出 {{ paginationConfig.total }} 条数据</span>
            <a-space>
              <a-checkbox @change="favoriteChange" v-model:checked="state.favorite"
                >我的收藏</a-checkbox
              >
              <a-button @click="aiGroupBtn('seeInfo')">查看入排条件</a-button>
              <a-button @click="programmeBtn">查看管理方案</a-button>
              <a-button @click="setGroup" v-auth="'hp-admin:patientManagement:doctor'"
                >分配医生</a-button
              >
              <a-button
                type="primary"
                v-auth="'hp-admin:patientManagement:save'"
                @click="addPatientBtn"
                >新增患者</a-button
              >
            </a-space>
          </div>
        </div>
        <div class="main">
          <!-- 表格 -->
          <a-table
            class="patientTable"
            :columns="state.columns"
            :data-source="state.table"
            :pagination="paginationConfig"
            :loading="tableLoading"
            @change="handleTableChange"
            size="small"
            :sticky="{ offsetHeader: 0 }"
          >
            <template #bodyCell="{ column, record, index }">
              <template v-if="column.dataIndex === 'num'">
                {{ (paginationConfig.current - 1) * paginationConfig.pageSize + index + 1 }}
              </template>
              <template v-if="column.key === 'groupNames'">
                <p v-if="record.groupNames">
                  <template v-for="tag in record.groupNames.slice(0, 4)" :key="tag">
                    <a-tag v-if="tag" class="configuration" :title="tag">
                      {{ tag }}
                    </a-tag>
                  </template>
                  <template
                    v-if="record.groupNames && record.groupNames.length > 4 && record.isGroud"
                  >
                    <template
                      v-for="tag in record.groupNames.slice(4, record.groupNames.length)"
                      :key="tag"
                    >
                      <a-tag v-if="tag" class="configuration" :title="tag">
                        {{ tag }}
                      </a-tag>
                    </template>
                  </template>
                </p>
                <a
                  v-if="record.groupNames && record.groupNames.length > 4"
                  @click="record.isGroud = !record.isGroud"
                  >{{ record.isGroud ? '收起' : '更多' }}</a
                >
              </template>
              <template v-else-if="column.key === 'planNames'">
                <p v-if="record.planNames">
                  <template v-for="tag in record.planNames.slice(0, 4)" :key="tag">
                    <a-tag v-if="tag" class="success" :title="tag">
                      {{ tag }}
                    </a-tag>
                  </template>
                  <template v-if="record.planNames && record.planNames.length > 4 && record.isPlan">
                    <template
                      v-for="tag in record.planNames.slice(4, record.planNames.length)"
                      :key="tag"
                    >
                      <a-tag v-if="tag" class="success" :title="tag">
                        {{ tag }}
                      </a-tag>
                    </template>
                  </template>
                </p>
                <a
                  v-if="record.planNames && record.planNames.length > 4"
                  @click="record.isPlan = !record.isPlan"
                  >{{ record.isPlan ? '收起' : '更多' }}</a
                >
              </template>
              <template v-else-if="column.key == 'userName'">
                {{ record.userName || '未分配' }}
              </template>
              <template v-else-if="column.key === 'action'">
                <a-button
                  type="link"
                  @click="patientDetailInfo(record.id, record.groupId, record.patId)"
                >
                  查看
                </a-button>

                <a-button
                  type="link"
                  @click="handleFavorite(record.favorite, record.id, record.patId)"
                  v-auth="'hp-admin:patientManagement:collect'"
                >
                  {{ record.favorite ? '取消收藏' : '收藏' }}
                </a-button>

                <a-button
                  type="link"
                  @click="handleDelete(record)"
                  v-auth="'hp-admin:patientManagement:delete'"
                >
                  删除
                </a-button>
              </template>
            </template>
          </a-table>
        </div>
      </div>
    </div>
    <patientInfo ref="patientInfoRef" @close="goBack" :childProp="state.doctorList" v-else />
    <AddPatient ref="addPatientRef" @close="goBack"></AddPatient>
    <Programme ref="programmeRef" :groupId="state.tab" @close="goBack"></Programme>

    <AiIntelligence ref="aiIntelligenceRef" @close="getGroupData"></AiIntelligence>
    <SetGroup ref="setGroupRef" @close="goBack"></SetGroup>
    <!-- <MessageDel ref="messageDelRef" @saveEvent="handleOk"></MessageDel> -->
  </div>
</template>

<script lang="ts" setup name="数据管理">
import { ref, reactive, onMounted, nextTick, createVNode, watch } from 'vue'
import {
  DownCircleOutlined,
  ExclamationCircleOutlined,
  ExclamationCircleFilled
} from '@ant-design/icons-vue'
import patientInfo from './patientInfo.vue'

import {
  getPatientList,
  getListByUser,
  getMyFavorite,
  addFavorite,
  cancelFavorite,
  deleteInfo,
  getUserList,
  getDoctorList
} from '@/api/patientManagement/index.ts'
import store from '@/store'
import AddPatient from './add-patient.vue'
import AiIntelligence from './ai-intelligence.vue'
import Programme from './programme.vue'
import { useRoute, useRouter } from 'vue-router'
import { message, Modal } from 'ant-design-vue'
import MessageDel from '@/components/MessageDel/index.vue'
import SetGroup from './set-group/index.vue'
const route = useRoute()

const state = reactive({
  showDetail: false,
  listActive: null,
  tabButtons: [],
  sex: '',
  doctor: '',
  doctorList: [],
  tab: '',
  tabName: '',
  group: [],
  groupList: [],
  // 搜索
  searchValue: '',
  // 表格
  totals: '0',
  columns: [
    {
      title: '序号',
      dataIndex: 'num',
      align: 'left',
      key: 'num',
      width: 70
    },
    {
      title: '姓名',
      dataIndex: 'patName',
      align: 'left',
      key: 'patName'
    },
    {
      title: '病案号',
      dataIndex: 'patId',
      align: 'left',
      key: 'patId'
    },
    {
      title: '性别',
      dataIndex: 'sexName',
      align: 'left',
      key: 'sexName',
      width: 80
    },
    {
      title: '年龄(岁)',
      key: 'age',
      align: 'left',
      dataIndex: 'age'
    },
    {
      title: '所属专病分组',
      dataIndex: 'groupNames',
      align: 'left',
      key: 'groupNames',
      minWidth: 150,
      ellipsis: true
    },
    {
      title: '入组时间',
      dataIndex: 'inGroupTime',
      align: 'left',
      key: 'inGroupTime'
    },
    {
      title: '当前管理方案',
      dataIndex: 'planNames',
      align: 'left',
      key: 'planNames',
      minWidth: 150,
      ellipsis: true
    },
    {
      title: '管理医生',
      dataIndex: 'userName',
      align: 'left',
      key: 'userName'
    },
    {
      title: '诊疗阶段',
      dataIndex: 'stage',
      align: 'left',
      key: 'stage'
    },
    {
      title: '操作',
      align: 'left',
      key: 'action'
    }
  ],
  table: [],
  favorite: false
})

const tableLoading = ref(true)

const maxTagCount = ref(2)
const aiIntelligenceRef = ref()
const programmeRef = ref()
const addPatientRef = ref()
const patientInfoRef = ref()
const messageDelRef = ref()
const setGroupRef = ref()

const paginationConfig = ref({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  pageSizeOptions: ['10', '20', '50', '100']
})

watch(route, () => {
  if (route.path == '/patientManagement/index') {
    state.showDetail = false
    getGroupData()
  }
})

onMounted(() => {
  if (route.query && route.query.groupId && route.query.patId) {
    patientDetailInfo(route.query.id, route.query.groupId, route.query.patId)
  } else {
    getGroupData()
  }
})

const getUserData = () => {
  state.doctorList = []
  getDoctorList({ groupId: state.tab }).then((res) => {
    state.doctorList = res.data
  })
}

const favoriteChange = (value) => {
  paginationConfig.value.current = 1
  state.searchValue = ''
  state.favorite = value.target.checked
  tableLoading.value = true
  getPatientData()
}

// 获取分组数据
const getGroupData = () => {
  state.tabButtons = []
  getListByUser()
    .then((res) => {
      if (res.data && res.data.length) {
        res.data.forEach((element) => {
          element.check = false
          state.tabButtons.push(element)
        })

        state.tabButtons[0].check = true
        state.tab = state.tabButtons[0].id
        state.tabName = state.tabButtons[0].groupName
      }
      if (state.tab) {
        getUserData()
        getPatientData()
      } else {
        tableLoading.value = false
        message.warning('暂无疾病分组数据，请添加分组')
      }
    })
    .catch(() => {
      tableLoading.value = false
    })

  if (route.query && route.query.groupId && route.query.patId) {
    patientDetailInfo(route.query.id, route.query.groupId, route.query.patId)
  }
}

// 患者列表
const getPatientData = () => {
  state.table = []
  paginationConfig.value.total = 0
  if (state.favorite) {
    state.sex = ''
    state.doctor = ''
    state.group = []
    getMyFavorite({
      page: paginationConfig.value.current,
      limit: paginationConfig.value.pageSize,
      order: '',
      asc: true,
      loginId: store.userApp.userInfo.id,
      tab: state.tab,
      favorite: true,
      patName: state.searchValue
    })
      .then((res) => {
        tableLoading.value = false
        if (res.data && res.data.list) {
          res.data.list.forEach((element) => {
            element.isGroud = false
            element.isPlan = false
          })
          state.table = res.data.list
          paginationConfig.value.total = res.data.total
        }
      })
      .catch(() => {
        tableLoading.value = false
      })
  } else {
    getPatientList({
      page: paginationConfig.value.current,
      limit: paginationConfig.value.pageSize,
      order: '',
      asc: true,
      tab: state.tab,
      sexCode: state.sex,
      groupId: state.group,
      loginId: store.userApp.userInfo.id,
      userId: state.doctor,
      patName: state.searchValue
    })
      .then((res) => {
        tableLoading.value = false
        if (res.data && res.data.list) {
          res.data.list.forEach((element) => {
            element.isGroud = false
            element.isPlan = false
          })
          state.table = res.data.list
          paginationConfig.value.total = res.data.total
        }
      })
      .catch(() => {
        tableLoading.value = false
      })
  }
}

const handleTableChange = (page, filters, sorter) => {
  paginationConfig.value = { ...page }
  tableLoading.value = true
  getPatientData()
}

const upfun = () => {
  state.listActive = !state.listActive
}
const selectGroup = (item) => {
  const data = state.tabButtons.filter((ele) => ele.id == item.id)[0]
  if (data.check) {
  } else {
    state.tabButtons.forEach((element) => {
      element.check = false
    })
    item.check = true
    state.tab = item.id
    state.tabName = item.groupName

    state.searchValue = ''
    state.doctor = ''
    tableLoading.value = true
    paginationConfig.value.current = 1
    getUserData()
    getPatientData()
  }
}
// 搜索
const handleSexChange = (val) => {
  state.sex = val

  onSearch()
}
const handleDoctor = (item) => {
  if (!item) {
    state.doctor = ''
  } else {
    state.doctor = item
  }

  onSearch()
}
const handleGroup = (item) => {
  state.group = item

  onSearch()
}

const onSearch = () => {
  tableLoading.value = true
  paginationConfig.value.current = 1
  getPatientData()
}

const resetEvent = () => {
  state.sex = ''
  state.doctor = ''
  state.group = []
  tableLoading.value = true
  onSearch()
}

const patientDetailInfo = (listId, id, patId) => {
  state.showDetail = true
  nextTick(() => {
    patientInfoRef.value.init(listId, id, patId)
  })
}

const handleFavorite = async (value, id, patId) => {
  if (!value) {
    await addFavorite({ id: id, patId: patId }).then((res) => {
      message.success('收藏成功')
    })
  } else {
    await cancelFavorite({ id: id, patId: patId }).then((res) => {
      message.success('取消收藏成功')
    })
  }

  tableLoading.value = true
  getPatientData()
}

// 删除
const handleDelete = (data) => {
  Modal.confirm({
    title: '删除',
    class: 'confirm',
    icon: createVNode(ExclamationCircleFilled, {
      style: {
        color: 'var(--color--danger)'
      }
    }),
    content: '确定删除该条数据吗',
    okText: '确定',
    okButtonProps: {
      danger: true,
      type: 'primary'
    },
    cancelText: '取消',
    onOk() {
      deleteInfo(data).then(() => {
        message.success('删除成功')
        tableLoading.value = true
        getPatientData()
      })
    },
    onCancel() {}
  })
  // messageDelRef.value.init(data)
}

// const handleOk = (data: any) => {
//   deleteInfo(data).then(() => {
//     message.success('删除成功')
//     tableLoading.value = true
//     getPatientData()
//   })
// }

const aiGroupBtn = (type) => {
  aiIntelligenceRef.value.init(type, state.tab)
}
const programmeBtn = () => {
  programmeRef.value.init()
}

const addPatientBtn = () => {
  addPatientRef.value.init(state.tab, state.tabName)
}

// 分配患者
const setGroup = () => {
  setGroupRef.value.init(state.tab)
}

const goBack = () => {
  state.showDetail = false
  nextTick(() => {
    tableLoading.value = true
    getUserData()
    getPatientData()
  })
}
</script>

<style lang="less" scoped>
.span-label {
  color: #000000d9;
}

.page {
  display: flex;
  flex-direction: column;
  height: calc(100vh - 80px);
  .listWrap {
    position: relative;
    overflow: hidden;

    display: flex;
    flex-direction: column;
    width: 100%;
    margin-bottom: 16px;
    flex: 0 0 auto;

    .list {
      padding: 0px 54px 0 24px;
      background: #fff;
      height: 64px;
      border-radius: 8px;

      .ant-btn {
        margin-top: 16px;
        display: inline-block;
        vertical-align: middle;

        &:nth-child(1) {
          margin-right: 16px;
        }
      }

      .tab_buttons {
        background: #f2f3f5;
        font-size: 14px;
        font-weight: 500;
        color: #1d2129;
        margin-right: 16px;
      }

      .checked {
        color: #165dff;
        background: #e8f3ff;
      }
    }

    .anticon {
      position: absolute;
      top: 22px;
      right: 24px;
      font-size: 20px;
      color: #86909c;
      transition: all 0.2s ease;

      &.on {
        transform: rotate(180deg);
      }
    }

    &.on {
      overflow: auto;

      .list {
        height: auto;
        padding: 0px 54px 16px 24px;
      }
    }
  }

  .body {
    width: 100%;
    margin-top: 16px;
    padding: 24px;
    background: #fff;
    border-radius: 8px;

    display: flex;
    flex-direction: column;
    height: calc(100% - 80px);

    .header {
      display: flex;
      flex-direction: column;
      width: 100%;
    }

    .main {
      flex: 1 1 auto;
      overflow: hidden auto;
    }

    .search_condition {
      width: 100%;
      overflow: hidden;
      margin-bottom: 16px;

      .search_select {
        float: left;
        margin-right: 32px;

        .ant-select {
          width: 210px;
          margin-left: 12px;
        }
      }

      // .search_input {
      //   float: right;
      // }
    }

    .total_operate {
      width: 100%;
      height: 32px;
      display: flex;
      justify-content: space-between;
      margin-bottom: 16px;

      span {
        display: inline-block;
        line-height: 50px;
      }
    }

    :deep(.patientTable) {
      .ant-table-tbody tr td {
        p {
          white-space: normal;
          margin-bottom: 0;

          .configuration {
            color: #3491fa;
            background: #e8f7ff;
            border-color: #3491fa;
            display: inline-block;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            max-width: 100%;
            margin-top: 10px;

            &:nth-child(1) {
              margin-top: 0;
            }
          }

          .success {
            color: #00b42a;
            background: #e8ffea;
            border-color: #00b42a;
            display: inline-block;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            max-width: 100%;
            margin-top: 10px;

            &:nth-child(1) {
              margin-top: 0;
            }
          }
        }
      }

      .ant-btn {
        padding: 4px 4px 4px 0;
      }
    }
  }
}

.search-form .ant-form-item {
  margin-bottom: 10px;
  .ant-input {
    width: 183px;
  }
}
.search-form .ant-select.ant-select-in-form-item {
  width: 183px;
}
</style>
